package com.wzy.interceptor;

import com.wzy.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用户权限的拦截器
 */
public class UserLoginInterceptor implements HandlerInterceptor {
    /**
     * 判断会话域中是否有用户的信息
     * 如果有就放行，没有就拦截
     * handler是 HandlerMethod对象
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //得到会话对象
        HttpSession session = request.getSession();
        //获取会话域中是否有用户对象
        User user = (User) session.getAttribute("user");
        //表示没有登录
        if (user==null){
            System.out.println("拦截到非法用户:"+request.getRemoteAddr());
            //异步操作，重定向不起作用
            response.sendRedirect(request.getContextPath()+"/login.html");
            //不再继续
            return false;
        }else {
            //放行
            return true;
        }
    }
}
